//时间戳位数：1619751776  获得单前时间时间戳：Math.round(new Date() / 1000)
const utils = {
    createRandomKey() {
        return Math.floor(Math.random() * (10, 1000000012313));
    },

    //数组分割成多个数组 arrList原 分割成多个数组，每个数组两个
    toSplit(arrList , size) {
        let index = 0;
        let setArr = [];
        while (index < arrList.length) {
            setArr.push(arrList.slice(index , index += size))
        }
        return setArr ;
    },

    //路由跳转新页面，解决window.open有时候 失效的问题
    asyncOpen(url) {
        let a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute("target", "_blank");
        a.setAttribute("download", 'name');
        document.body.appendChild(a);
        a.click();
        a.remove();
    },
    // 时间戳转换成时间，只转化到日期没有到时间和秒 2017-08-25
    timeDate(timeStamp) {
        let date = timeStamp13(timeStamp);
        let year = date.getFullYear();
        let month = dateFormat(date, 1);
        let day = dateFormat(date, 2);
        return year + '-' + month + '-' + day;
    },

    // 时间戳转换成时间，到月 2017-08
    timeDate1(timeStamp) {
        let date = timeStamp13(timeStamp);
        let year = date.getFullYear();
        let month = dateFormat(date, 1);
        return year + '-' + month;
    },

    // 时间戳转换成日期只到秒  2021-04-01 12:36:16
    timeDateSeconds(timeStamp) {
        let date = timeStamp13(timeStamp);
        let year = date.getFullYear();
        let month = dateFormat(date, 1);
        let day = dateFormat(date, 2);
        let hours = dateFormat(date, 3);
        let minutes = dateFormat(date, 4);
        let seconds = dateFormat(date, 5);
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    },

    //日期转换成时间戳 2015-05-10 14:25:55 转成10位数时间戳
    stampData(time) {
        let date = new Date(time.replace(/-/g, '/'));
        return date.getTime() / 1000;
    },

    //日期转换成时间戳 2015-05-10 14:25:55 转成13位数时间戳
    //日期转换成时间戳  转成13位数时间戳
    // type 1 正常的日期转换成时间戳 2015-05-10 14:25:55
    // type 2  月份转换成时间戳  202308
    // type 3  年转换成时间戳  2023
    stampData13(time, type = 1) {
        if (!time) {
            return ''
        }
        let date = "";
        if (typeof time != 'string') {
            time = time.toString();
        }
        let year = time.substring(0, 4);
        let month = time.slice((time.length - 2), time.length)
        switch (type) {
            case 1:
                date = new Date(time.replace(/-/g, '/'));
                break;
            case 2:
                date = `${year}-${month}-01`
                date = new Date(date.replace(/-/g, '/'));
                break
            case 3:
                date = `${year}-01-01`
                date = new Date(date.replace(/-/g, '/'));
                break
        }
        return date.getTime();
    },

    /*过去当前日期和过去的日期*/
    // getDay(0) 当前日期
    // getDay(-7) 前七天
    // 返回 2021-05-13
    getDay(num) {
        let date = new Date();
        let targetDayMilliseconds = date.getTime() + 1000 * 60 * 60 * 24 * num; // 将目标日转换成毫秒
        date.setTime(targetDayMilliseconds);
        let year = date.getFullYear();
        let month = dateFormat(date, 1);
        let day = dateFormat(date, 2);
        return year + "-" + month + "-" + day;
    },

    // 返回 2021-05-13 10:49:48
    getDaySecond(num) {
        let date = new Date();
        let targetDayMilliseconds = date.getTime() + 1000 * 60 * 60 * 24 * num;
        date.setTime(targetDayMilliseconds);
        let year = date.getFullYear();
        let month = dateFormat(date, 1);
        let day = dateFormat(date, 2);
        let hours = dateFormat(date, 3);
        let minutes = dateFormat(date, 4);
        let seconds = dateFormat(date, 5);
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    },

    //返回当前时间   num 0 当前时间 -7 前7天
    //type 1  2021-05-13 10:49:48  年月日时分秒
    //type 2  2021-05-13  年月日
    //type 3  202105 年月
    //type 4  2021 年
    currentTime(num, type = 1) {
        let date = new Date();
        let targetDayMilliseconds = date.getTime() + 1000 * 60 * 60 * 24 * num;
        date.setTime(targetDayMilliseconds);
        let year = date.getFullYear();
        let month = dateFormat(date, 1);
        let day = dateFormat(date, 2);
        let hours = dateFormat(date, 3);
        let minutes = dateFormat(date, 4);
        let seconds = dateFormat(date, 5);
        switch (type) {
            case 1:
                return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
            case 2:
                return year + "-" + month + "-" + day
            case 3:
                return year.toString()+ month.toString()
            case 4:
                return year.toString()
        }
    },


    //实时时间
    //1 2021-05-13 10:49:48 星期4
    //2 2021年05月13日 星期4
    //3 2021-05-13 10:49:48
    getNowDate(type) {
        let date = new Date();
        let sign1 = "-";
        let sign2 = ":";
        let year = date.getFullYear() // 年
        let month = date.getMonth() + 1; // 月
        let day = date.getDate(); // 日
        let hour = date.getHours(); // 时
        let minutes = date.getMinutes(); // 分
        let seconds = date.getSeconds() //秒
        let weekArr = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        let week = weekArr[date.getDay()];
        // 给一位数数据前面加 “0”
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (day >= 0 && day <= 9) {
            day = "0" + day;
        }
        if (hour >= 0 && hour <= 9) {
            hour = "0" + hour;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        let currentdate = null;
        switch (type) {
            case 1:
                currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds + " " + week;
                break;
            case 2:
                currentdate = year + "年" + month + "月" + day + "日 " + week;
                break;
            case 3:
                currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds + " ";
                break;
        }
        return currentdate;
    },

    // 指定日期后加几年  传入13位时间戳  加后几年 得到 2015-15-12
    getYearTime(timeStamp, numYear) {
        let date = timeStamp13(timeStamp, 2);
        let year = date.getFullYear() + numYear;
        let month = dateFormat(date, 1);
        let day = dateFormat(date, 2);
        return year + '-' + month + '-' + day;
    },

    //2021-10-25T08:53:53.000Z成日期  {{Utils.dateChangeFormat('YYYY-mm-dd HH:MM:SS',scope.row[item.field])}}
    dateChangeFormat(format, date) {
        date = new Date(date);
        const dataItem = {
            'Y+': date.getFullYear().toString(),
            'm+': (date.getMonth() + 1).toString(),
            'd+': date.getDate().toString(),
            'H+': date.getHours().toString(),
            'M+': date.getMinutes().toString(),
            'S+': date.getSeconds().toString(),
        };
        Object.keys(dataItem).forEach((item) => {
            const ret = new RegExp(`(${item})`).exec(format);
            if (ret) {
                format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
            }
        });
        return format;
    },

    //计算两个时间之间的时间差传的是十位时间戳 多少天时分秒 默认:天 时 分 秒  1:到分
    intervalTime(startTime, endTime, type) {
        let date1 = startTime; //开始时间
        let date2 = endTime; //结束时间
        if (!endTime) { //还没结束时间
            return
        }
        let date3 = (date2 - date1) * 1000; //时间差的毫秒数

        //计算出相差天数
        let days = Math.floor(date3 / (24 * 3600 * 1000));
        //计算出小时数
        console.log(date3)
        let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
        let hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数
        let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
        let minutes = Math.floor(leave2 / (60 * 1000));

        //计算相差秒数
        let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
        let seconds = Math.round(leave3 / 1000);
        switch (type) {
            case 1:
                return days + "天 " + hours + "小时 " + minutes + "分"
            default:
                return days + "天 " + hours + "小时 " + minutes + "分" + seconds + "秒"
        }
    },

    //数字转化成大写 123转化成 壹百贰拾叁元整
    moneyToCapital(n) {
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
            return "数据非法";  //判断数据是否大于0
        }
        let unit = "千百拾亿千百拾万千百拾元角分", str = "";
        n += "00";
        let indexpoint = n.indexOf('.');  // 如果是小数，截取小数点前面的位数
        if (indexpoint >= 0) {
            n = n.substring(0, indexpoint) + n.substr(indexpoint + 1, 2);   // 若为小数，截取需要使用的unit单位
        }
        unit = unit.substr(unit.length - n.length);  // 若为整数，截取需要使用的unit单位
        for (let i = 0; i < n.length; i++) {
            str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);  //遍历转化为大写的数字
        }
        return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整"); // 替换掉数字里面的零字符，得到结果
    },

    //英文首字母大写
    englishInitialCapital(val) {
        return val.charAt(0).toUpperCase() + val.slice(1)
    },



    //加法精度问题
    numberAdd(num1, num2) {
        let r1, r2, m;
        try {
            r1 = num1.toString().split('.')[1].length

        } catch (e) {
            r1 = 0
        }
        try {
            r2 = num2.toString().split('.')[1].length
        } catch (e) {
            r2 = 0
        }
        m = Math.pow(10, Math.max(r1, r2))
        return (Math.trunc(num1 * m) + Math.trunc(num2 * m)) / m
    },
    //延迟执行函数
    //使用
    // (async () => {
    //     for (let i = 0; i < 10; i++) {
    //         await this.delay(1000);
    //         console.log("hello!");
    //     }
    // })();
    async delay(time) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    },

    //返回二个数有几个小数点
    multiplicationPrecision() {
        var x = 4;//测试的数字
        var y = String(x).indexOf(".") + 1;//获取小数点的位置
        var count = String(x).length - y;//获取小数点后的个数
        if (y > 0) {
            alert("这个数字是小数，有" + count + "位小数");
        } else {
            alert("不是小数");
        }
    }


}

//根据项目来定，默认传入的是10位时间戳  默认是1
function timeStamp13(timeStamp, num = 1) {
    let stamp
    switch (num) {
        case 1:
            stamp = timeStamp * 1000;//这个是把十位的时间戳转换成13位时间戳
            break
        case 2:
            stamp = timeStamp;//这个可以根据该默认值来执行
    }
    return new Date(stamp);
}

//处理完后输出
function process(params) {
    return params < 10 ? ('0' + params) : params;
}

//月 小于10，显示的时候前面加个0   num 1:月 2:日 3:时 4:分 5:秒
function dateFormat(date, num) {
    switch (num) {
        case 1:
            return process(date.getMonth() + 1);
        case 2:
            return process(date.getDate());
        case 3:
            return process(date.getHours());
        case 4:
            return process(date.getMinutes());
        case 5:
            return process(date.getSeconds());
    }
}

module.exports = utils

